package com.kj.platformlogistics.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.kj.platformlogistics.CaptureActivity;
import com.kj.platformlogistics.R;
import com.kj.platformlogistics.base.BaseActivity;
import com.kj.platformlogistics.login.LoginActivity;
import com.kj.platformlogistics.util.SPUtils;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    private static final int REQUEST_CODE = 101;
    private int REQUEST_CODE_SCAN=102;
    private int from = 0;
    private NoScrollViewPager vpContent;
    private MainPageController pageController;
    boolean isExit = false;//退出程序标识
    private String apkUrl="";

    private ImageView ivHome,ivMy,ivScan;
    private TextView tvHome,tvScan,tvMy;
    private LinearLayout llMy,llHome,llScan;

    @Override
    protected void init(Bundle savedInstanceState) { setAndroidNativeLightStatusBar(true); }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_main;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initView() {
        from = getIntent().getIntExtra("from", 0);
        vpContent = findViewById(R.id.vpContent);
        ivHome=findViewById(R.id.ivHome);
        ivMy=findViewById(R.id.ivMy);
        ivScan=findViewById(R.id.ivScan);
        llMy=findViewById(R.id.llMy);
        tvHome=findViewById(R.id.tvHome);
        llScan=findViewById(R.id.llScan);
        llHome=findViewById(R.id.llHome);
        tvMy=findViewById(R.id.tvMy);
        tvScan=findViewById(R.id.tvScan);
        llScan.setOnClickListener(this::onClick);
        llMy.setOnClickListener(this);
        llHome.setOnClickListener(this::onClick);

        pageController = new MainPageController(MainActivity.this, vpContent);
        switch (from) {
            case 0:
                reSetStatus();
                ivHome.setImageResource(R.mipmap.icon_selected_home);
                tvHome.setTextColor(getResources().getColor(R.color.red));
                break;
            case 1:
                reSetStatus();
                ivMy.setImageResource(R.mipmap.icon_selected_my);
                tvMy.setTextColor(getResources().getColor(R.color.red));
                break;
        }

        from = 0;
        pageController.ChangePage(0);
        setAndroidNativeLightStatusBar(true);
    }


    @Override
    protected void initData() { }

    @Override
    public int getTitleBarType() {
        return TITLEBAR_NULL;
    }

    /**
     * from = 0，首页
     * @param context
     * @param i
     */
    public static void actionStart(Context context, int i) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("from", i);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            switch (from) {
                case 0:
                    exitByDoubleClick();
                    break;
                case 1:
                case 2:
                    from = 0;
                    reSetStatus();
                    ivHome.setImageResource(R.mipmap.icon_selected_home);
                    setAndroidNativeLightStatusBar(true);
                    pageController.ChangePage(0);
                    break;
            }
        }
        return false;
    }

    //双击返回退出
    private void exitByDoubleClick() {
        Timer tExit = null;
        if (!isExit) {
            isExit = true;
            Toast.makeText(this, "再返回一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;//取消退出
                }
            }, 2000);// 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            finish();
            System.exit(0);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llMy:
                from=1;
                reSetStatus();
                ivMy.setImageResource(R.mipmap.icon_selected_my);
                tvMy.setTextColor(getResources().getColor(R.color.red));
                pageController.ChangePage(2);
                setAndroidNativeLightStatusBar(true);
                break;
            case R.id.llHome:
                from=0;
                reSetStatus();
                ivHome.setImageResource(R.mipmap.icon_selected_home);
                tvHome.setTextColor(getResources().getColor(R.color.red));
                pageController.ChangePage(0);
                setAndroidNativeLightStatusBar(true);
                break;
            case R.id.llScan:
                reSetStatus();
                tvScan.setTextColor(getResources().getColor(R.color.red));
                checkPermission();
                break;
        }
    }

    /****权限**/
    private void checkPermission(){
        try{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (PermissionChecker.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)!= PermissionChecker.PERMISSION_GRANTED||
                        PermissionChecker.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PermissionChecker.PERMISSION_GRANTED||
                        PermissionChecker.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_BACKGROUND_LOCATION)!=PermissionChecker.PERMISSION_GRANTED) {
                    // 不相等 请求授权
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA,
                            Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_BACKGROUND_LOCATION
                    },REQUEST_CODE);
                }else {
                    initLocation();
                    //扫描二维码
                    //二维码扫一扫
                    Intent intent = new Intent(getContext(), CaptureActivity.class);
                    /**ZxingConfig是配置类
                     *可以设置是否显示底部布局，
                     * 闪光灯，相册 是否播放提示音  震动
                     * 设置扫描框颜色等 也可以不传这个参数
                     * */
                    ZxingConfig config = new ZxingConfig();
                    config.setPlayBeep(true);//是否播放扫描声音 默认为true
                    config.setShake(true);//是否震动  默认为true
                    config.setDecodeBarCode(true);//是否扫描条形码 默认为true
                    config.setReactColor(R.color.white);//设置扫描框四个角的颜色 默认为白色
                    config.setFrameLineColor(R.color.white);//设置扫描框边框颜色 默认无色
                    config.setScanLineColor(R.color.white);//设置扫描线的颜色 默认白色
                    config.setFullScreenScan(true);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                    config.setShowFlashLight(true);
                    intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("aaa", "onRequestPermissionsResult: " +
                            "权限申请成功");
                    for (int i : grantResults) {
                        Log.d("aaa", "onRequestPermissionsResult: " + i);
                    }
                    //扫码开始
                    //二维码扫一扫
                    initLocation();
                    Intent intent = new Intent(getContext(), CaptureActivity.class);
                    /**ZxingConfig是配置类
                     *可以设置是否显示底部布局，
                     * 闪光灯，相册 是否播放提示音  震动
                     * 设置扫描框颜色等 也可以不传这个参数
                     * */
                    ZxingConfig config = new ZxingConfig();
                    config.setPlayBeep(true);//是否播放扫描声音 默认为true
                    config.setShake(true);//是否震动  默认为true
                    config.setDecodeBarCode(true);//是否扫描条形码 默认为true
                    config.setShowFlashLight(true);
                    config.setReactColor(R.color.white);//设置扫描框四个角的颜色 默认为白色
                    config.setFrameLineColor(R.color.white);//设置扫描框边框颜色 默认无色
                    config.setScanLineColor(R.color.white);//设置扫描线的颜色 默认白色
                    config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                    intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                } else {
                    Toast.makeText(MainActivity.this, "您已拒绝申请权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }


    public void reSetStatus(){
        ivHome.setImageResource(R.mipmap.icon_unselected_home);
        tvHome.setTextColor(getResources().getColor(R.color.gray9));
        ivMy.setImageResource(R.mipmap.icon_unselected_my);
        tvScan.setTextColor(getResources().getColor(R.color.gray9));
        tvMy.setTextColor(getResources().getColor(R.color.gray9));
    }

    private String lat="";
    private String lng="";

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    lat=amapLocation.getLatitude()+"";
                    lng=amapLocation.getLongitude()+"";
                   SPUtils.setSharedStringData(MainActivity.this,"lat",lat);
                   SPUtils.setSharedStringData(MainActivity.this,"lng",lng);

                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    public void initLocation(){

        //初始化定位
        mLocationClient = new AMapLocationClient(MainActivity.this);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //单次定位
        mLocationOption.setOnceLocation(true);
        //启动定位
        mLocationClient.startLocation();
    }
}